package com.vogue.api.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vogue.api.data.CateringUser;
import com.vogue.api.mapper.CateringUserMapper;
import com.vogue.api.common.security.model.Oauth2User;
import com.vogue.api.common.security.model.UserInfo;
import com.vogue.api.service.CateringUserService;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.stereotype.Service;

/**
 * 用户记录表
 * @author George<qiaozhi_china@163.com>
 */
@Service("cateringUserService")
public class CateringUserServiceImpl extends ServiceImpl<CateringUserMapper, CateringUser> implements CateringUserService {

    private WxMaService service;

    @Override
    public Oauth2User findImUserByUserAccount(String userAccount) {
        CateringUser imUser = baseMapper.findImUserByUserAccount(userAccount);
        return new Oauth2User(imUser.getUserId().longValue(), imUser.getNickName(), imUser.getMobile(), imUser.getAvatar());
    }

    @Override
    public Oauth2User findImUserByUserOpenId(String openId, UserInfo userInfo) {
        CateringUser imUser = baseMapper.findImUserByUserOpenId(openId);
        if (ObjectUtil.isEmpty(imUser)){
            imUser=new CateringUser();
            BeanUtil.copyProperties(userInfo,imUser);
            imUser.setOpenId(openId);
            imUser.setAvatar(userInfo.getAvatarUrl());
            imUser.setUpdateTime(DateUtil.date());
            imUser.setCreateTime(DateUtil.date());

            save(imUser);
        }
        return new Oauth2User(imUser.getUserId().longValue(), imUser.getNickName(), imUser.getMobile(), imUser.getAvatar());
    }

    @Override
    public Oauth2User loadUserByMobileAndPassword(String mobile, String password) {
        if (org.springframework.util.StringUtils.isEmpty(mobile) || org.springframework.util.StringUtils.isEmpty(password)) {
            throw new InvalidGrantException("您输入的手机号或密码不正确");
        }
        // 判断成功后返回用户细节
        CateringUser imUser = baseMapper.loadUserByMobileAndPassword(mobile, password);
        return new Oauth2User(imUser.getUserId().longValue(), imUser.getNickName(), imUser.getMobile(), imUser.getAvatar());
    }

    @Override
    public Oauth2User loadUserByMobileAndSmsCode(String mobile) {
        if (org.springframework.util.StringUtils.isEmpty(mobile)) {
            throw new InvalidGrantException("您输入的手机号不正确");
        }
        // 判断成功后返回用户细节
        CateringUser imUser = baseMapper.loadUserByMobileAndSmsCode(mobile);
        return new Oauth2User(imUser.getUserId().longValue(), imUser.getNickName(), imUser.getMobile(), imUser.getAvatar());
    }

}
